﻿using EdgeSearch.Core.Entity.LogDB;
using Microsoft.Extensions.Logging;

namespace EdgeSearch.Application.Manager.LogManager
{
    public class DatabaseLoggingWriter : IDatabaseLoggingWriter
    {
        private readonly DatabaseLoggingManager _dbLoggingManager;

        public DatabaseLoggingWriter(DatabaseLoggingManager dbLoggingManager)
        {
            _dbLoggingManager = dbLoggingManager;
        }

        /// <summary>
        /// 记录全局日志
        /// </summary>
        /// <param name="logMsg"></param>
        /// <param name="flush"></param>
        public void Write(LogMessage logMsg, bool flush)
        {
            var model = new LogInfo
            {
                CreateDate = DateTime.Now,
                ErrorLevel = GetLogLevelString(logMsg.LogLevel),
                ErrorSource = 0,
                ProjectID = int.Parse(App.Configuration["Logging:DataBase:ProjectID"]),
                UserID = int.Parse(App.Configuration["Logging:DataBase:UserID"]),
                ErrorMsg = logMsg.Message,
            };
            //审计日志存在日志上下文
            var logContext = logMsg.Context;
            if (logContext is not null && logContext.Properties.Count > 0)
            {
                model.ErrorMsg = logContext.Get("loggingMonitor").ToString();
                model.PageUrl = logContext.Get("PageUrl").ToString();
                model.Method = logContext.Get("Action").ToString();
            }
            else if (logMsg.Exception is not null)
            {
                //其它异常日志加入堆栈信息
                model.ErrorMsg += logMsg.Exception.StackTrace;
            }
            _dbLoggingManager.AddDBLog(model);
        }

        /// <summary>
        /// 获取日志级别短名称
        /// </summary>
        /// <param name="logLevel">日志级别</param>
        /// <returns></returns>
        internal static string GetLogLevelString(LogLevel logLevel)
        {
            return logLevel switch
            {
                LogLevel.Trace => "DEBUG",
                LogLevel.Debug => "DEBUG",
                LogLevel.Information => "INFO",
                LogLevel.Warning => "WARN",
                LogLevel.Error => "ERROR",
                LogLevel.Critical => "FATAL",
                LogLevel.None => "FATAL",
                _ => logLevel.ToString().ToUpper(),
            };
        }
    }
}
